package com.quasar.hpatient.module.mine_info;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.widget.ImageView;

import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.comm_album.AlbumPhotoBean;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.compress.CompressManager;
import lib.quasar.compress.OnCompressChangeListener;
import lib.quasar.context.BaseConstant;
import lib.quasar.db.manager.DBManager;
import lib.quasar.db.table.User;
import lib.quasar.util.CardUtil;
import lib.quasar.util.ImageUtil;
import lib.quasar.util.LogUtil;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * description: 我 ==> 个人资料
 * created by kalu on 2018/7/16 15:41
 */
public final class MineInfoPresenter implements BasePresenter {

    final void loadInfo(final MineInfoView view) {

        final User user = DBManager.getInstance().syncGetUserModel();
        view.setInfo(user);

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.USER_TYPE, HttpParams.USER_PATIENT);
        map.put(HttpParams.USER_ID, getPatientId());
        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_1_2);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().mineInfo(params);

        request(observable, new OnModelAcceptChangeListener<User>() {
            @Override
            public void modelSucc(User result) {
                DBManager.getInstance().setUserModel(result);
                final User user = DBManager.getInstance().syncGetUserModel();
                view.setInfo(user);
            }
        });
    }

    final void pushInfo(final MineInfoView view, final String icard,final String name,
                        final String icon, final String sex, final String birthday, final String blood, final String master, final String sample,
                        final String type, final String form, final String time, final String hotpital, final String phone, final String address) {

        final User user = DBManager.getInstance().syncGetUserModel();
        user.setIcard(icard);
        user.setIcon(icon);
        user.setReal_name(name);
        user.setSexs(sex);
        user.setBirthday(birthday);
        user.setBlood_type(blood);
        user.setSupervisor_doctor(master);
        user.setDonor_receptor_type(sample);
        user.setTransplant_type(type);
        user.setSource_type(form);
        user.setOperation_date(time);
        user.setHospital_name(hotpital);
        user.setPhone(phone);
        user.setAddress(address);
        DBManager.getInstance().updataUserModel(user);

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.ICON, user.getIcon());
        map.put(HttpParams.REAL_NAME, user.getReal_name());
        map.put(HttpParams.SEX, user.getSex());
        map.put(HttpParams.BIRTHDAY, user.getBirthday());
        map.put(HttpParams.BLOOD_TYPE, user.getBlood_type());
        map.put(HttpParams.SUPERVISOR_DOCTOR, user.getSupervisor_doctor());
        map.put(HttpParams.DONOR_RECEPTOR_TYPE, user.getDonor_receptor_type());
        map.put(HttpParams.TRANSPLANT_TYPE, user.getTransplant_type());
        map.put(HttpParams.SOURCE_TYPE, user.getSource_type());
        map.put(HttpParams.OPERATION_DATE, user.getOperation_date());
        map.put(HttpParams.HOSPITAL_NAME, user.getHospital_name());
        map.put(HttpParams.PHONE, user.getPhone());
        map.put(HttpParams.ADDRESS, user.getAddress());
        map.put(HttpParams.ICARD, user.getIcard());

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_1_13);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().uploadData(params);

        request(observable, new OnModelAcceptChangeListener<Object>() {
            @Override
            public void modelSucc(Object result) {
                view.toast("保存信息成功");
            }

            @Override
            public void modelFail() {
                view.toast("保存信息失败");
            }
        });
    }

    @SuppressLint("CheckResult")
    final void compressPhoto(final MineInfoView view, ImageView image, AlbumPhotoBean model) {

        Observable.create((ObservableOnSubscribe<AlbumPhotoBean>) e -> {
            String path = model.getPicture();
            String name = path.substring(path.lastIndexOf(File.separatorChar), path.length());
            final int width = model.getWidth();
            final int height = model.getHeight();
            final long size = model.getSize();
            // 获取bitmap
            if (!model.needCompress()) {
                final AlbumPhotoBean news = new AlbumPhotoBean();
                news.setPicture(path);
                news.setCheck(model.isCheck());
                news.setWidth(width);
                news.setHeight(height);
                news.setSize(size);
                e.onNext(model);

            } else {

                final Bitmap bitmap = ImageUtil.compressImageJava(path, model.calcuWidth(), model.calcuHeight());
                final String floder = CardUtil.getSDCardPath() + BaseConstant.CACHE_COMPRESS;

                // 压缩图片
                CompressManager.syncCompress(true, model.getRatio(), floder, name, bitmap, new OnCompressChangeListener() {
                    @Override
                    public void onCompressStart() {
                    }

                    @Override
                    public void onCompressFinish(String filePath) {

                        if (null != bitmap) {
                            bitmap.recycle();
                        }

                        final AlbumPhotoBean news = new AlbumPhotoBean();
                        news.setPicture(filePath);
                        news.setCheck(model.isCheck());
                        news.setWidth(width);
                        news.setHeight(height);
                        news.setSize(size);
                        e.onNext(news);
                    }

                    @Override
                    public void onCompressError(int errorNum, String description) {

                        if (null != bitmap) {
                            bitmap.recycle();
                        }
                    }
                });
            }
        }).subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(temp -> {
                            uploadPhoto(view, image, temp);
                            //  ToastUtil.showToast("分线程: 压缩图片结束");
                        }, throwable -> {
                            // ToastUtil.showToast("分线程: 压缩图片失败");
                            LogUtil.e("", throwable.getMessage(), throwable);
                        },
                        () -> {
                            // ToastUtil.showToast("分线程: 压缩图片结束");
                        },
                        disposable -> {
                            // ToastUtil.showToast("分线程: 开始压缩图片");
                        });
    }

    final void uploadPhoto(final MineInfoView view, ImageView image, AlbumPhotoBean model) {

        if (null == view || null == image)
            return;

        final HashMap<String, RequestBody> map = new HashMap<>();

        final String imagePath = model.getPicture();
        final File file = new File(imagePath);
        final RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        map.put("file" + 0 + "\"; filename=\"" + file.getName() + "\"", body);

        HashMap<String, Object> params2 = new HashMap<>();
        params2.put(HttpParams.INSPECTIONDATE, getDate());
        final RequestBody params = createParams(params2, HttpParams.DATA_TYPE_412);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().uploadPhoto(params, map);

        request(observable, new OnModelAcceptChangeListener<List<AlbumPhotoBean>>() {

            @Override
            public void modelSucc(List<AlbumPhotoBean> model) {

                image.setTag(-110, model.get(0).getPicture());
                view.setImage(image, model.get(0).getUrl(), true);
            }
        });
    }

    @Override
    public void recycler() {
    }
}
